import { Article, Channel } from '@/types/data'
import { RootAction } from '@/types/store'

type InitType = {
  userChannels: Channel[]
  allChannels: Channel[]
  activeId: number
  channelArticles: {
    [key: number]: {
      timestamp: string
      articles: Article[]
    }
  }
}

const initValue: InitType = {
  userChannels: [], // 用户自己的频道
  allChannels: [], // 所有的频道
  activeId: -1, // 高亮项id
  channelArticles: {},
}

export function homeReducer(
  state: InitType = initValue,
  action: RootAction
): InitType {
  if (action.type === 'home/set_user_Channels') {
    return {
      ...state,
      userChannels: action.payload,
    }
  }

  if (action.type === 'home/set_all_Channels') {
    return {
      ...state,
      allChannels: action.payload,
    }
  }

  if (action.type === 'home/set_active_id') {
    return {
      ...state,
      activeId: action.payload,
    }
  }

  if (action.type === 'home/set_channel_articles') {
    const { channel_id, timestamp, articles } = action.payload

    // h5 网页是没有分页的效果的, 上拉加载, 数据是追加式的, 数据是越来越多!!! 需要合并老数据
    // const oldArticles = state.channelActicles[channel_id].articles || []
    const oldArticles = state.channelArticles[channel_id]?.articles || []

    return {
      ...state,
      channelArticles: {
        ...state.channelArticles,
        [channel_id]: {
          timestamp: timestamp,
          articles: [...oldArticles, ...articles],
        },
      },
    }
  }

  if (action.type === 'home/refresh_articles') {
    const { channel_id, timestamp, articles } = action.payload
    return {
      ...state,
      channelArticles: {
        ...state.channelArticles,
        [channel_id]: {
          timestamp,
          articles: [...articles],
        },
      },
    }
  }
  return state
}
